package com.mings.ai.config;

import com.knuddels.jtokkit.api.EncodingType;
import org.springframework.ai.embedding.BatchingStrategy;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.embedding.TokenCountBatchingStrategy;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPooled;

@Configuration
public class TagConfig {

    @Value("${spring.data.redis.host:localhost}")
    private String redisHost;

    @Value("${spring.ai.vectorstore.redis.index-name:spring-ai-index}")
    private String indexName;

    @Value("${spring.ai.vectorstore.redis.prefix:embedding:}")
    private String prefix;

    @Bean
    public BatchingStrategy embeddingBatchingStrategy() {
        return new TokenCountBatchingStrategy(EncodingType.CL100K_BASE, 132900, 0.1);
    }

    @Bean
    @ConditionalOnMissingBean
    public JedisPooled jedisPooled() {
        return new JedisPooled(redisHost, 6379);
    }

    @Bean
    public VectorStore vectorStore(JedisPooled jedisPooled,
                                   EmbeddingModel embeddingModel) {
        return RedisVectorStore.builder(jedisPooled, embeddingModel)
                .indexName(indexName)
                .prefix(prefix)
                .initializeSchema(true)
                .metadataFields(RedisVectorStore.MetadataField.text("source"))
                .build();
    }
}